<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/7/31
 * Time: 上午9:51
 */

namespace Hrm\Controllers;

use Admin\Models\device\XhsysUsertablet;
use Admin\Models\hrm\XhhrmResource;
use Admin\Models\hrm\XhhrmStaffUser;
use Admin\Models\sys\XhsysEnum;
use Bpm\Controllers\PlanController;
use Helpers\Cache;
use Helpers\Hrm;
use Helpers\HttpClient;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Helpers\Template;
use Helpers\Main;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\XhException;
use Hrm\Models\XHHrmAttendence;
use Modules\Power;
use Services\HundredMail;

class StaffController extends ControllerBase
{

    private static $enums = [
        'bMarried' => [1 => '已', 0 => '未'],
        'iWorkStatus' => [
            1 => '兼职',
            2 => '实习',
            3 => '全职',
            4 => '应届',
        ],
        'iStaffStatus' => [
            1 => '在职',
            2 => '离职',
            3 => '退休',
        ],
        'iOfferStatus' => [
            1 => '试用',
            2 => '正式',
            3 => '非正式',
            4 => '其他'
        ],
        'iSignIn' => ['1' => '正常', 2 => '未打卡', 3 => '迟到'],
        'iSignOut' => ['1' => '正常', 2 => '未打卡', 3 => '早退'],
        'iSignStatus' => ['1' => '正常', 2 => '隔天', 3 => '请假', 4 => '调休'],
        'bOvertime' => ['0' => '否', '1' => '是'],
        'iUserSex' => ['1' => '男', 2 => '女'],
        'bSpecial' => [0 => '正常',1 =>'特殊']
    ];


    private static $state = [
        0 => '新建',
        1 => '未录取',
        2 => '待入职',
        3 => '未入职',
        4 => '已入职',
    ];

    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['code' => 404, 'error' => 'page not found!']);
    }


    /**
     * 创建
     * @param $detail
     * @param $msg
     * @return bool
     * created by dale 2017/8/17
     */
    public function praseLog($detail, $msg)
    {
        return Main::createCommitLog(
            'hrm',
            $this->dispatcher->getControllerName(),
            $this->dispatcher->getActionName(),
            ['post' => $this->request->getPost(), 'get' => $this->request->getQuery(), 'detail' => $detail],
            null,
            $msg
        );
    }

    /**
     * 员工信息
     *
     * created by dale 2017/11/18
     *  弃用
     */
    public function staffInfoAction()
    {
        UserPower::checkUserPower('Hrm_Staff') or die('缺少权限');
        $this->view->pick('staff/staffInfo');
        $id = $this->request->getQuery('id', 'string') or die('缺少id');
        if(!$id){
            return $this->sendViewError('缺少参数');
        }
        $staffInfo = XhhrmStaff::findFirst([
            'conditions' => 'bDelete=0 AND iStaffId=:iStaffId:',
            'bind' => array('iStaffId' => $id),
        ]);

        if (!$staffInfo) {
            return $this->sendViewError('没找到该职工');
        }else{
            $staffInfo = $staffInfo->toArray();
        }

//        if ($staffInfo['tBirthday'] != null) {
//            $staffInfo['iAge'] = $this->getAge($staffInfo['tBirthday']);
//        }
//        if ($staffInfo['tHireDate'] != null) {
//            $staffInfo['sCompanyYear'] = $this->getAge($staffInfo['tHireDate']);
//        }

        $staffInfo['sDepName'] = XhhrmDepart::getDepName($staffInfo['sDepIds']);

        if ($staffInfo['sPrIcon'] == null) {
            $icon = 'default';
        } else {
            $icon = Main::getConfigByName('hrm')['downUrl'] . $staffInfo['sPrIcon'];
        }
        Assets::datetimePicker();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/staff/staffInfo.js');
        $this->view->setVars([
            'staff' => $staffInfo,
            'staffInfo' => json_encode($staffInfo),
            'icon' => $icon,
        ]);
    }





    /**
     * 计算年龄
     * @param $birthday
     * @return bool|string
     * created by dale 2017817
     */
    function getAge($birthday)
    {
        list($year, $month, $day) = explode("-", $birthday);
        $year_diff = date("Y") - $year;
        $month_diff = date("m") - $month;
        $day_diff = date("d") - $day;
        if ($day_diff < 0 || $month_diff < 0) //未到生日
            $year_diff--;
        return $year_diff;
    }


    /**
     * 职工列表
     *
     * created by dale 2017817
     * modify by dale 20181211  导入工号时未处理名单导出
     */
    public function StaffListAction()
    {
        UserPower::checkUserPower('Hrm_Staff') or die('缺少权限');
        Assets::easyUI();
        Assets::datetimePicker();
        Assets::excelLentExport();
        Assets::sweetAlert2();
        Assets::select2();
        Assets::importJs('js/staff/staffList.js');
//        Assets::importMainJs('assets/xh/xhTop.js');
        Main::showNavPosition();
        $this->view->pick('staff/staffList');

        $enum = [
            '1' => '所有',
            '2' => '负责人',
        ];
        $enums = self::$enums;
        $enums['iWorkStatus'][''] = '工作状态';
        $enums['iStaffStatus'][''] = '职工状态';
        $enums['iOfferStatus'][''] = '录用状态';
        Template::exists('staffList', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if (UserPower::checkUserPower('Hrm_Staff_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add_menu', 'text' => '员工录入', 'class' => 'bt_list_menu');
//            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_import_menu', 'text' => '信息导入', 'class' => 'bt_list_menu');
//            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_import', 'text' => '人员导入', 'icon' => 'fa-plus');
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_addStaffNumber', 'text' => '新增工号', 'icon' => 'fa-plus');
        }
        if (UserPower::checkUserPower('Hrm_Staff_Edit')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_importStaffNumber', 'text' => '工号导入', 'icon' => 'fa-pencil');
        }
        if (UserPower::checkUserPower('Hrm_Staff_Edit')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_move', 'text' => '转移', 'icon' => 'fa-pencil');
        }
        if (UserPower::checkUserPower('Hrm_Staff_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        if (UserPower::checkUserPower('User_UserList_SetPower')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_set_power', 'text' => '设置权限', 'icon' => 'fa-pencil');
        }
        if (UserPower::checkUserPower('Hrm_Staff_ViewPower')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_view_power', 'text' => '查看权限', 'icon' => 'fa-eye');
        }
        if (Main::getLoginUserInfo('logonName') == 'admin') {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_account', 'text' => '账号关联', 'icon' => 'fa-pencil');
        }
        if (UserPower::checkUserPower('Hrm_Staff_Group')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_group', 'text' => '设置角色', 'icon' => 'fa-pencil');
        }
        if (UserPower::checkUserPower('Hrm_Staff_ViewPower')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_viewHistory', 'text' => '查看操作历史', 'icon' => 'fa-eye');
        }



        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_setCharge', 'text' => '设置负责人', 'icon' => 'fa-pencil');
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_info', 'text' => '查看详情', 'icon' => 'fa-eye');
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_wstatus', 'text' => '工作状态', 'class' => 'bt_list_menu');
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_sstatus', 'text' => '职工状态', 'class' => 'bt_list_menu');
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_ostatus', 'text' => '录用状态', 'class' => 'bt_list_menu');
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_special', 'text' => '设置特殊', 'class' => 'bt_list_menu');
//        if (UserPower::checkUserPower('Hrm_Staff_Edit')) {
//            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_transfer', 'text' => '员工调动', 'icon' => 'fa-pencil');
//        }
        if (UserPower::checkUserPower('Hrm_Staff_Edit')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_seeEmail', 'text' => '查看百分邮箱', 'icon' => 'fa-eye');
        }

        $listSearchArr[] = array('type' => 'select', 'id' => 'select_all', 'data' => $enum, 'default' => '1');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_special', 'data' => [1 => '特殊', 0 => '全部'], 'default' => '0');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_work', 'data' => $enums['iWorkStatus'], 'default' => '');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_staff', 'data' => $enums['iStaffStatus'], 'default' => '1');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_offer', 'data' => $enums['iOfferStatus'], 'default' => '');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_export_staff', 'text' => '导出', 'icon' => 'fa fa-file-excel-o');
//        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_export_staffNumber', 'text' => '工号模板导出', 'icon' => 'fa fa-file-excel-o');
        if (!UserPower::checkUserPower('Hrm_Staff_Edit')) {
            $staffEdit = '#bt_list_status{
                            display: none; 
                        }';
        } else {
            $staffEdit = '';
        }
        $this->view->setVars(array(
            'staffList' => Template::createList('staffList', 'staffList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
            'staffEdit' => $staffEdit,
            'enums' => self::$enums
        ));
    }

    /**
     * 获取职工列表信息
     *
     * @param $offWork
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 2017814
     * modify by dale 20180322
     */
    public function getStaffDataAction($offWork = false)
    {
        $key = $this->request->getPost('key', 'string'); //可以为空
        $iDepId = $this->request->getPost('depId', 'string');
        $all = $this->request->getPost('all', 'string');
        $workstate = $this->request->getPost('workstate', 'string');
        $staffstate = $this->request->getPost('staffstate', 'string');
        $offerstate = $this->request->getPost('offerstate', 'string');
        $sort  = $this->request->getPost('sort', 'string');
        $order  = $this->request->getPost('order', 'string');
        $special = $this->request->getPost('special', 'string');
        if ($sort && $sort == 'sDepName') {
            $sort = 'sDepIds';
        }
        $data = XhhrmStaff::getStaffList([
            'key'      => $key,
            'depId'    => $iDepId,
            'bManager' => $all,
            'bOffWork' => $offWork,
            'workStatus' => $workstate,
            'staffStatus' => $staffstate,
            'offerStatus' => $offerstate,
            'special' => $special,
            'sort' => $sort,
            'order' => $order,
//            'fields' => [
//                'iUserId','iStaffId','sStaffName','sChargeDeps','sDepIds','sSelfPhone','iWorkStatus','iOfferStatus',
//                'iStaffStatus','sStaffNumber','sHundredMail','tBirthday','tHireDate','bMarried','sNationName','sNativePlace',
//                'bMarried','iUserSex','sNowAddress','sFamilyAddress','sIdentityCode','tCreateDate'
//            ]
        ]);

        $phones = array_values(array_unique(array_filter(array_column($data['rows'], 'sSelfPhone'))));//除空
        $newArray = [];//备用机数组
        if ($phones != []) {
            $tablets = XhsysUsertablet::find([
                'columns' => 'sReceiverPhone,iReceivePurpose,iUTId',
                'conditions' => 'bDone = 0 AND bDelete = 0  AND sReceiverPhone in ({phones:array})',
                'bind' => ['phones' => $phones],
                'order' => 'sReceiverPhone,iReceivePurpose',
            ])->toArray();
            foreach ($tablets as $row) {
                $newArray[$row['sReceiverPhone']][$row['iReceivePurpose']][] = $row;
            }
        }
        foreach ($data['rows'] as $index => $row) {
            if ($row['iUserId'] == null) {
                $data['rows'][$index]['infoImage'] = '';
            } else {
                $color = $this->changeColor($row['sChargeDeps'], $row['bDisable'], $row['iStaffStatus']);
                $data['rows'][$index]['infoImage'] = '<i class="fa fa-user" style="color:' . $color . ';" title="' . $row['iUserId'] . '"></i>';
            }
            $data['rows'][$index]['infoTablet'] = $this->getTabletStr($row['sSelfPhone'], $newArray);
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 根据职工状态 是否禁用 设置 图标颜色
     *
     * @param $sChargeDeps
     * @param $bDisable
     * @param $iStaffStatus
     *
     * @return string
     *
     * create by dale  20181224
     */
    public function changeColor($sChargeDeps, $bDisable,$iStaffStatus)
    {
        if ($bDisable == '1' && $iStaffStatus == '离职' ) {
            return '#CCCCCC';
        } else {
            $color = '#2baab1';
            if ($sChargeDeps != null) {
                $color = '#0066cc';
            }
        }
        return $color;
    }

    /**
     * 获取职工领用平板的信息
     *
     * @param $phoneNum
     * @param $array
     *
     * @return string
     *
     * create by dale  20181224
     */
    public function getTabletStr($phoneNum, $array)
    {
        if (!isset($array[$phoneNum])) {
            return '';
        } else {
            $color = '';
            $strArr = [];
            if (isset($array[$phoneNum][0])) {
                $strArr[] = '自用' . count($array[$phoneNum][0]);
                $color = 'green';
            }
            if (isset($array[$phoneNum][1])) {
                $strArr[] = '备用' . count($array[$phoneNum][1]);
                $color = '#663333';
            }
            if (isset($array[$phoneNum][0]) && isset($array[$phoneNum][1])) {
                $color = '#0033cc';
            }
            $str = implode(',', $strArr);
            return '<i class="fa fa-tablet"  title="' . $str . '" style="color:' . $color . ';" ></i>';
        }
    }


    /**
     * 导入表单
     *
     * create by dale 2017814
     * modify by dale 20181224  弃用
     */
    public function importFormAction()
    {
        UserPower::checkUserPower('Hrm_Staff_Add') or die('缺少权限');
        $this->view->pick('staff/importForm');
        Assets::importMainJs('assets/jquery/jquery.form.js');
        Assets::importMainJs('assets/xh/xhExtra.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/staff/importForm.js');

    }

    /**
     * 添加表单
     *
     * created by dale 2017814
     */
    public function addFormAction()
    {
        if (!Power::exist('Hrm_Staff_Add')) {
            return $this->sendViewError('缺少权限');
        }
        $this->view->pick('staff/addForm');
//        Assets::importJs('js/myMain.js');
        Assets::importMainJs('assets/xh/xhForm.js');
//        Assets::datetimePicker();
//        Assets::easyUI();
        Assets::importJs('js/staff/addForm.js');
        $this->view->setVars([
            'staffInfo' => '1',
            'iStaffStatus' => self::$enums['iStaffStatus'],
            'iOfferStatus' => self::$enums['iOfferStatus'],
            'iWorkStatus' => self::$enums['iWorkStatus'],
            'iStaffLevel' => XhsysEnum::getEnumByNodeName('职位等级'),
        ]);
    }




    /**
     * 编辑表单
     *
     * created by dale 201796
     * modify by dale 20181224  弃用
     */
    public function editFormAction($iStaffId)
    {
        UserPower::checkUserPower('Hrm_Staff_Edit') or die('缺少权限');
        $this->view->pick('staff/addForm');
        Assets::importJs('js/myMain.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::datetimePicker();
        Assets::importJs('js/staff/editForm.js');
        $staff = XhhrmStaff::findFirst($iStaffId);
        $staff = $staff->toArray();
//        $staff['tGraduateDate']=date('Y-m',strtotime($staff['tGraduateDate']));
//        $staff['tStartWork']=date('Y-m',strtotime($staff['tStartWork']));
        $this->view->setVars([
            'staffInfo' => json_encode($staff),
            'iStaffStatus' => self::$enums['iStaffStatus'],
            'iOfferStatus' => self::$enums['iOfferStatus'],
            'iWorkStatus' => self::$enums['iWorkStatus'],
            'iStaffLevel' => XhsysEnum::getEnumByNodeName('职位等级'),
        ]);
    }


    public function getDepAction()
    {
        $newArray[0]['iDepId'] = 0;
        $newArray[0]['sDepName'] = '全部';
        $newArray[0]['iconCls'] = 'fa fa-group';
        $newArray[0]['children'] = $this->recursionForArray(0);

        return json_encode($newArray);
    }

    /**
     * 带权限的部门树
     *
     * @return string  json
     *
     * create by dale 20171211
     */
    public function getDepWithPowerAction()
    {
        if (Main::getLoginUserInfo('logonName') == 'admin' || UserPower::checkUserPower('AddrBook_All')) {
//        if (Main::getLoginUserInfo('logonName') == 'admin') {
            $newArray[0]['iDepId'] = 0;
            $newArray[0]['sDepName'] = '全部';
            $newArray[0]['iconCls'] = 'fa fa-group';
            $newArray[0]['children'] = $this->recursionForArray(0);
        } else {
            $iUserId = Main::getLoginUserInfo('userId');
            $staff = XhhrmStaff::findFirst([
                'conditions' => 'iUserId = :iUserId:',
                'bind' => ['iUserId' => $iUserId],
            ]);
            if (!$staff) {
                die('用户不存在');
            }
            $ids = explode(',', $staff->sDepIds);
            $ids = array_values(array_filter($ids));
            if ($ids == []) {
                die('不属于任何部门');
            }
            $currentId = end($ids);
            $newArray[0]['iDepId'] = $currentId;
            $newArray[0]['sDepName'] = XhhrmDepart::getDepEnum()[$currentId];
            $newArray[0]['iconCls'] = 'fa fa-group';
            $newArray[0]['children'] = $this->recursionForArray($currentId);
        }
        return json_encode($newArray);
    }

    /**
     * 导出staff
     *
     * @throws XhException
     *
     * create by dale
     * modify by dale 20181224  添加修改 XhrmStaffGetList
     */
    public function exportStaffAction()
    {
        $this->view->disable();
        $key = $this->request->getQuery('key', 'string'); //可以为空
        $iDepId = $this->request->getQuery('depId', 'string');
        $all = $this->request->getQuery('all', 'string');
        $workstate = $this->request->getQuery('workstate', 'string');
        $staffstate = $this->request->getQuery('staffstate', 'string');
        $offerstate = $this->request->getQuery('offerstate', 'string');
        $data = XhhrmStaff::getStaffList([
            'key'      => $key,
            'depId'    => $iDepId,
            'bManager' => $all,
            'workStatus' => $workstate,
            'staffStatus' => $staffstate,
            'offerStatus' => $offerstate,
        ], false);
        $phones = array_values(array_unique(array_filter(array_column($data, 'sSelfPhone'))));//除空
        $tablets = XhsysUsertablet::find([
            'columns' => 'sReceiverPhone,iReceivePurpose,iUTId',
            'conditions' => 'bDone = 0 AND bDelete = 0  AND sReceiverPhone in ({phones:array})',
            'bind' => ['phones' => $phones],
            'order' => 'sReceiverPhone,iReceivePurpose',
        ])->toArray();
        $newArray = [];   //备用机数组
        foreach ($tablets as $row) {
            $newArray[$row['sReceiverPhone']][$row['iReceivePurpose']][] = $row;
        }
        foreach ($data as $index => $row) {
            if (isset($newArray[$row['sSelfPhone']])) {
                if (isset($newArray[$row['sSelfPhone']][1])) {
                    $data[$index]['iRepBackNum'] = count($newArray[$row['sSelfPhone']][1]);//备用
                }
                if (isset($newArray[$row['sSelfPhone']][0])) {
                    $data[$index]['iRepSelfNum'] = count($newArray[$row['sSelfPhone']][0]);//自用
                }
            }
        }
        $title = [
            'sStaffName' => '职工姓名',
            'sPostName' => '岗位',
            'sIdentityCode' => '身份证号',
            'sDepName' => '部门',
            'sStaffNumber' => '工号',
            'sHundredMail' => '百分邮箱',
            'sSelfPhone' => '联系方式',
            'tHireDate' => '入职日期',
            'tRegularDate' => '转正日期',
            'sProbationDate' => '试用期',
            'iOfferStatus' => '身份类别',
            'iWorkStatus' => '员工分组',
            'iUserSex' => '性别',
            'tBirthday' => '出生年月',
            'iAge' => '年龄',
            'sFamilyAddress' => '户籍地址',
            'iRegisterType' => '户籍性质',
            'sNowAddress' => '现居住地',
            'sNationName' => '民族',
            'sNativePlace' => '籍贯',
            'sCultureLevel' => '最高学历',
            'sProfession' => '专业',
            'sPostLevel' => '职称',
            'tStartWork' => '参加工作时间',
            'sCompanyYear' => '司龄',
            'sContentDate' => '合同期限',
            'iSignNumber' => '签订次数',
            'sContractStatus' => '合同领用情况',
            'sSocialPayDate' => '社保缴纳开始月份',
            'sSocialPayStatus' => '社保缴纳情况',
            'sSurplusPayDate' => '公积金缴纳月份',
            'sSurplusPayRate' => '公积金基数',
            'sSurplusPayStatus' => '公积金缴纳情况',
            'sInsuranceDate' => '意外险缴纳时间',
            'sBankCard' => '招商银行卡号',
            'sBankInfo' => '支行信息',
            'sContractName' => '紧急联络人',
            'sContractRelation' => '与本人关系',
            'sContractPhone' => '联系人电话',
            'bMarried' => '婚否',
            'sRemark' => '备注',
            'iStaffStatus' => '职工状态',
            'tLeaveTime' => '离职时间',
            'sLeaveReason' => '离职理由',
            'iRepBackNum' => '备用机数目',
            'iRepSelfNum' => '自用机数目'

        ];
        $dataSource = [];
        foreach ($data as $key => $row) {
            foreach ($title as $filed => $name) {
                $dataSource[$key][$filed] = isset($row[$filed]) ? $row[$filed] : '';
            }
        }
        $fileName = '职工信息_' . Main::getLoginUserInfo('userName');
        $this->praseLog('导出职工信息', '导出职工信息');
        Tool::exportExcelOnline($fileName, $title, $dataSource, 'xlsx');
    }


    /**
     * 根据父id递归数组
     * @param $parentId
     * @return array
     *
     * created by dale 2017814
     */
    public function recursionForArray($parentId)
    {
        $parameters = array(
            'conditions' => "bDelete=:bDelete: AND iParentId=:parentId: ",
            'bind' => array('parentId' => $parentId, 'bDelete' => 0),
        );
        $objs = XhhrmDepart::find($parameters);
        if ($objs == null) {
            return [];
        }
        $array = $objs->toArray();
        $newArray = [];
        foreach ($array as $key => $value) {
            $newArray[$key] = $value;
            $newArray[$key]['iconCls'] = 'fa fa-group';
            $newArray[$key]['children'] = $this->recursionForArray($value['iDepId']);
            if ($newArray[$key]['children']) {
                $newArray[$key]['state'] = "closed";
            }
        }
        return $newArray;
    }

    /**
     * 根据数组递归网页
     *
     * @param $array
     * @return string
     *
     * created by dale 2017814
     */
    public function recursionForHtml($array)
    {
        $contentStr = '';
        foreach ($array as $key => $value) {
            if ($value == end($array)) {
                $contentStr .= '<li class="openable last-link"><a nodeid="' . $value['iDepId'] . '"><i class="fa fa-group m-right-xs "></i>' . $value['sDepName'] . '</a>';
            } else {
                $contentStr .= '<li class="openable"><a nodeid="' . $value['iDepId'] . '"><i class="fa fa-group m-right-xs "></i>' . $value['sDepName'] . '</a>';
            }
            if ($value['children'] != []) {
                $contentStr .= '<ul class="subtree">' . $this->recursionForHtml($value['children']) . ' </ul>';
            }
            $contentStr .= '</li>';
        }
        return $contentStr;
    }


    /**
     * 将人员添加到组
     *
     * @param $isResource
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 2017814
     * modify by dale 20180327
     */
    public function moveGroupAction($isResource=false)
    {
        UserPower::checkUserPower('Hrm_Staff_Add') or die('缺少权限');
        $this->view->disable();
        $iDepId = $this->request->getPost('depId', 'string') or die('缺少参数');
        $staffIds = $this->request->getPost('staffIds', 'string');
        $staffIds or die('缺少staffIds');
        $staffIds = explode(',', $staffIds);

        $userId = Main::getLoginUserInfo('userId');
        $sDepIds = $this->getDepIds($iDepId);
        if(!$isResource){
            $staffs = XhhrmStaff::find([
                'conditions' => 'bDelete=0 AND iStaffId in ({ids:array})',
                'bind' => array('ids' => $staffIds)
            ]);
        }else{
            $staffs = XhhrmResource::find([
                'conditions' => 'bDelete=0 AND iStaffId in ({ids:array})',
                'bind' => array('ids' => $staffIds)
            ]);
        }
        $flag = false;
        foreach ($staffs as $staff) {
            if($staff->iUserId != $userId){
                $staff->sDepIds = $sDepIds;
                if (!$staff->save()) {
                    $this->praseLog('添加到组失败', '添加到组失败');
                    return $this->response->setContent('error');
                }
            }else{
                $flag =true;
            }
        }
        if(!$flag){
            $this->praseLog('添加到组成功', '添加到组成功');
            return $this->response->setContent('success');
        }else{
            return $this->sendErrorResponse(500,'转移自己失败');
        }

    }


    /**
     * 获取到sDepIds
     *
     * @param $iDepId
     * @return string
     *
     * created by dale 2017817
     */
    public function getDepIds($iDepId)
    {
        $iDepIds = [];
        $iDepIds = $this->recursionForIds($iDepId, $iDepIds);
        $sDepIds = ',';
        foreach ($iDepIds as $id) {
            $sDepIds .= $id . ',';
        }

        return $sDepIds;
    }

    /**
     * 获取部门名称通过名字
     *
     * @param $sDepName
     * @return string
     *
     * create by dale 2017817
     */
    public function getDepIdsByName($sDepName)
    {
        $dep = XhhrmDepart::findFirst([
            'column' => 'iDepId',
            'conditions' => 'bDelete=0 AND sDepName=:sDepName:',
            'bind' => array('sDepName' => $sDepName)
        ]);

        return $this->getDepIds($dep->iDepId);
    }

    /**
     * 循环递归获取父部门id
     *
     * @param $iDepId
     * @param $array
     * @return array
     *
     * created by dale 2017817
     */
    public function recursionForIds($iDepId, $array)
    {
        $nowDep = XhhrmDepart::findFirst([
            'conditions' => 'bDelete=0 AND iDepId=:iDepId:',
            'bind' => array('iDepId' => $iDepId)
        ]);
        $array[] = $nowDep->iDepId;
        if ($nowDep->iParentId == 0) {
            return $array;
        } else {
            return $this->recursionForIds($nowDep->iParentId, $array);
        }
    }


    /**
     *  保存职工信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017814
     * modify by dale 20171211
     * modify by dale 20181219  该方法只支持 手动创建职工账号
     */
    public function saveStaffAction()
    {
        try {
            $postData = $this->request->getPost();
            $iDepId = $this->request->getPost('iDepId');
            if (!Power::exist('Hrm_Staff_Add')) {
                return $this->sendErrorResponse(403, '缺少权限');
            }
            if (!$postData['sStaffName'] || !$postData['sIdentityCode']) {
                return $this->sendErrorResponse(400, '缺少必要参数');
            }
            if ($postData['iStaffId']) {
                return $this->sendErrorResponse(500, '该接口不支持修改');
            }
            if (!XhhrmStaff::checkIdentityCode($postData['sIdentityCode'])) {
                return $this->sendErrorResponse(500, '该身份号码已经存在');
            };
            if ($iDepId) {
                $postData['sDepIds'] = $this->getDepIds($iDepId);
            }
            XhhrmStaff::addStaff($postData);
            return $this->sendJsonResponse(['code' =>  200, 'msg' =>'创建成功'], true);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }



    /**
     * 删除职工信息
     *
     * @param $isResource
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 2017814
     */
    public function delStaffAction($isResource=false)
    {
        UserPower::checkUserPower('Hrm_Staff_Del') or die('缺少权限');
        $this->view->disable();
        $staffIds = $this->request->getPost('ids', 'string');
        $staffIds or die('缺少id');
        $staffIds = explode(',', $staffIds);
        //删除staff记录
        if(!$isResource){
            $staffs = XhhrmStaff::find([
                'conditions' => 'bDelete=0 AND iStaffId in ({ids:array})',
                'bind' => array('ids' => $staffIds)
            ]);
        }else{
            $staffs = XhhrmResource::find([
                'conditions' => 'bDelete=0 AND iStaffId in ({ids:array})',
                'bind' => array('ids' => $staffIds)
            ]);
        }
        foreach ($staffs as $staff) {
            $staff->bDelete = 1;
            if (!$staff->save()) {
                $this->praseLog('删除失败', '职工信息删除失败');
                return $this->response->setContent('删除失败');
            }
        }
        $this->praseLog('职工信息删除成功', '职工信息删除成功');
        return $this->response->setContent('删除成功');
    }

    /**
     * 图片上传
     *
     * @param $file
     * @param $id
     * @return string
     *
     * created by dale 2017818
     */
    public function uploadImage($file, $id)
    {
        $this->view->disable();
        $savePath = Main::getConfigByName('hrm')['savePath'];
        //$savePath = 'hrm/prIcon';
        if (!is_dir($savePath)) {
            mkdir($savePath, 0777, true) or die($savePath . '创建失败');
        }
        $fileName = md5_file($file->getTempName()) . '.' . $file->getExtension();
        $filePath = $savePath . '/' . $id;
        if (!is_dir($filePath)) {
            mkdir($filePath, 0777, true) or die($filePath . '创建失败');
        }
        $filePath = $savePath . '/' . $id . '/' . $fileName;
        $url = $id . '/' . $fileName;
        $file->moveTo($filePath);
        return $url;
    }

    /**
     * 导入职工信息
     *
     * @return string
     * created by dale 2017/8/14
     */
//    public function importStaffAction()
//    {
//        UserPower::checkUserPower('Hrm_Staff_Add') or die('缺少权限');
//        return $this->sendErrorResponse(500, '导入功能完善中');
////        $file = $this->request->getUploadedFiles()[0];
////        //var_dump($file);
////        $fileName = md5_file($file->getTempName()) . '.' . $file->getExtension();
////        $savePath = TEMP_PATH;
////        //$savePath = 'hrm/excel';
////        if (!is_dir($savePath)) {
////            mkdir($savePath, 0777, true) or die($savePath . '创建失败');
////        }
////        $filePath = $savePath . '/' . $fileName;
////        $file->moveTo($filePath);
//
////        require_once dirname(dirname(__DIR__)) . '/../common/library/PHPExcel/PHPExcel.php';
//        try {
//
////            $kk = Tool::readExcel($filePath, true);
////
////            $field = [
////                '序号' => '',
////                '部门' => 'sDepName',               //需修改
////                '姓名' => 'sStaffName',
////                '性别' => 'iUserSex',
////                '年龄' => '',
////                '出生日期' => 'tBirthday',
////                '岗位' => 'sPostName',
////                '民族' => 'sNationName',
////                '籍贯' => 'sNativePlace',
////                '联系电话' => 'sSelfPhone',
////                '最高学历' => 'sCultureLevel',
////                '毕业院校' => 'sGraduateSchool',
////                '专业' => 'sProfession',
////                '职称' => 'sPostLevel',
////                '户籍地址' => 'sFamilyAddress',
////                '身份证号码' => 'sIdentityCode',
////                '家庭住址' => 'sNowAddress',
////                '参加工作时间' => 'tStartWork',
////                '入职时间' => 'tHireDate',
////                '司龄（年）' => '',
////                '转正时间' => 'tRegularDate',
////                '合同期限' => 'sContentDate',
////                '签订次数' => 'iSignNumber',
////                '合同领用情况' => 'sContractStatus',
////                '社保缴纳时间' => 'tSocialPayDate',
////                '社保缴纳情况' => 'sSocialPayStatus',
////                '公积金缴纳情况' => 'sSurplusPayStatus',
////                '招商银行卡号' => 'sBankCard',
////                '紧急联络人' => 'sContractName',
////                '与本人关系' => 'sContractRelation',
////                '联系人电话' => 'sContractPhone',
////                '婚否' => 'bMarried',
////                '备注' => 'sRemark',
////            ];
////            foreach ($title[0] as $index => $value) {   //将数组和序号关联起来
////                if ($value && $field[$value]) {
////                    $title[1][$index] = $field[$value];
////                }
////            }
////            //var_dump($kk);die();
////            foreach ($kk as $index => $value) {
////                $obj = new XhhrmStaff();
////                $obj->sCreateMode = 'staff_import';
////                foreach ($title[1] as $col => $ifield) {
////
////                    if ($ifield == 'sDepName') {
////                        $obj->sDepIds = $this->getDepIdsByName($value[$col]);
////                        continue;
////                    }
////                    if ($ifield == 'iUserSex') {
////                        if ($value[$col] == '男') {
////                            $obj->iUserSex = 1;
////                        } else {
////                            $obj->iUserSex = 2;
////                        }
////                        continue;
////                    }
////                    if ($ifield == 'tStartWork') {
////                        $obj->$ifield = strval($value[$col]) . '.00';
////                        continue;
////                    }
////                    if ($ifield == 'bMarried') {
////                        if ($value[$col] == '未') {
////                            $obj->$ifield = 0;
////                        } else {
////                            $obj->$ifield = 1;
////                        }
////                        continue;
////                    }
////
////
////                    $obj->$ifield = $value[$col];
////                    $obj->iStaffStatus = 1;
////                }
////                if ($this->checkStaff($obj->sStaffName, $obj->sIdentityCode)) {
////                    $res = $obj->save();
////                    if (!$res) {
////                        return $this->response->setContent('error');
////                    } else {
////                        try {
////                            $re = $this->createNewAccount(strval($obj->sSelfPhone), $obj->sStaffName);
////                            if ($re) {
////                                $this->praseLog('User创建成功', 'User创建成功,name:' . $obj->sStaffName . '电话:' . $obj->sSelfPhone . ',初始密码:123456');
////                                $this->uploadUserId(strval($obj->sSelfPhone), $obj->sStaffName);
////                            }
////                        } catch (\Exception $e) {
////                            $this->praseLog('User创建失败', 'User创建失败,信息:' . $e->getMessage());
////                            return $this->sendErrorResponse(500, $e->getMessage());
////                        }
////                    }
////                }
////            }
////            unlink($filePath);
////            return $this->response->setContent(json_encode(array('message' => '插入成功')));
//
//        } catch (\Exception $e) {
//            return $this->response->setContent($e->getMessage());
//        }
//
//    }

    public function checkStaff($sStaffName, $sIdentityCode)
    {
        $checked = XhhrmStaff::findFirst([
            'conditions' => 'bDelete=0 AND sStaffName=:sStaffName: AND sIdentityCode=:sIdentityCode:',
            'bind' => array('sStaffName' => $sStaffName, 'sIdentityCode' => $sIdentityCode)
        ]);
        if ($checked) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 展示员工所拥有账号
     *
     * create by ck 20170902
     */
    public function staffAccountAction()
    {
        $this->view->pick('staff/staffAccount');
        Assets::importJs('js/staff/staffAccount.js');
        if (Main::getLoginUserInfo('logonName') != 'admin') {
            return $this->flash->error('无操作权限！');
        }
        $staffId = $this->request->getQuery('staffId', 'int');
        if (!$staffId) {
            return $this->flash->error('缺少员工id！');
        }
        $staff = XhhrmStaff::findFirst($staffId);
        if (!$staff) {
            return $this->flash->error('找不到员工记录！');
        }
        $params = [
            'columns' => 'iUserId,sUserName,sLogonName,sSelfPhone,bDisable',
            'conditions' => 'sSelfPhone = :phoneNum: OR sLogonName = :phoneNum:',
            'bind' => ['phoneNum' => $staff->sSelfPhone]
        ];
        if ($staff->iUserId) {
            $params['conditions'] .= ' OR iUserId = :userId:';
            $params['bind']['userId'] = $staff->iUserId;
        }
        $userList = XhsysUser::find($params)->toArray();
        if (!$userList) {
            return $this->flash->error('找不到员工所属账号!');
        }
        if ($staff->iUserId) {
            foreach ($userList as $index => $user) {
                if ($staff->iUserId == $user['iUserId']) {
                    $userList[$index]['sUserName'] .= "<font style='color: red;'>(已关联)</font>";
                }
            }
        }
        $this->view->setVar('accountList', $userList);
        $staffUser = $this->modelsManager->createBuilder()
            ->columns('s.iSUId,s.sLogonName,s.mDesc,u.iUserId,u.sUserName,u.sSelfPhone,u.bDisable')
            ->from(['s' => 'Admin\\Models\\hrm\\XhhrmStaffUser'])
            ->leftJoin('Admin\\Models\\user\\XhsysUser', 'u.iUserId = s.iUserId', 'u')
            ->where('s.bDelete = 0 and s.iStaffId = :staffId:', ['staffId' => $staffId])
            ->getQuery()->execute()->toArray();
//        var_dump($staffUser);die;
        if ($staffUser) {
            $this->view->setVar('staffUser', $staffUser);
        }
        return true;
    }

    /**
     * 保存职工账号关系
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180822
     */
    public function saveStaffUserAction(){
        try {
            $loginName = $this->request->getPost('loginName','string');
            $staffId    = $this->request->getPost('staffId','int');
            $desc = $this->request->getPost('desc', 'string');
            if (!$loginName || !$staffId ) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $userId = XhsysUser::findFirst([
                'columns'    => 'iUserId',
                'conditions' => 'bDelete = 0 and ( sLogonName = :sLogonName: or sSelfPhone = :sLogonName:  )',
                'bind'       => ['sLogonName' => $loginName]
            ]);
//            if (!$userId) {
//                return $this->sendErrorResponse(500, '未找到账号对应的用户');
//            }
            $check = XhhrmStaffUser::findFirst([
                'conditions' => 'bDelete = 0 and sLogonName = :sLogonName: and iStaffId = :iStaffId:',
                'bind'       => ['sLogonName' => $loginName ,'iStaffId' => $staffId],
            ]);
            if ($check) {
                return $this->sendErrorResponse(500, '该账号已经存在,请勿重复关联');
            }
            $obj = new XhhrmStaffUser();
            if ($userId) {
                $obj->iUserId  = $userId->iUserId;
            }
            $obj->iStaffId = $staffId;
            $obj->mDesc    = $desc;
            $obj->sLogonName  = $loginName;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendJsonResponse(['code'=>200,'msg'=>'保存成功']);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e instanceof \Helpers\XhException ? $e->getDescription() : $e->getTrace());
        }
    }

    /**
     * 删除职工账号关系
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180822
     */
    public function delStaffUserAction(){
        try {
            $id = $this->request->getPost('id', 'int');
            if (!$id) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XhhrmStaffUser::findFirst($id);
            if(!$obj->delete()) {
                return $this->sendErrorResponse(500, '删除失败');
            }
            return $this->sendJsonResponse(['code'=>200,'msg'=>'删除成功']);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e instanceof \Helpers\XhException ? $e->getDescription() : $e->getTrace());
        }
    }

    /**
     * 关联员工用户id
     *
     * @param bool|false $disContact
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170902
     */
    public function staffContactAction($disContact = false)
    {
        $staffId = $this->request->getPost('staffId', 'int');
        $userId = $this->request->getPost('userId', 'int');
        if (!$staffId || !$userId) {
            return $this->response->setStatusCode(400)->setJsonContent(['error' => '缺少必要参数！']);
        }
        $staff = XhhrmStaff::findFirst($staffId);
        if (!$staff) {
            return $this->response->setStatusCode(400)->setJsonContent(['error' => '找不到员工记录！']);
        }
        if ($disContact) {
            if ($userId != $staff->iUserId) {
                return $this->response->setStatusCode(400)->setJsonContent(['error' => '该记录未关联！']);
            }
            $staff->iUserId = null;
        } else {
            $checkContact = XhhrmStaff::findFirst([
                'conditions' => 'bDelete = 0 and iUserId = :iUserId: and iStaffId != :iStaffId:',
                'bind'       => ['iUserId' => $userId, 'iStaffId' => $staffId],
            ]);
            if ($checkContact) {
                return $this->response->setStatusCode(400)->setJsonContent(['error' => '该账号已被关联！']);
            }
            $staff->iUserId = $userId;
        }
        if (!$staff->save()) {
            return $this->response->setStatusCode(500)->setJsonContent(['error' => '操作失败！']);
        }
        return $this->response->setJsonContent(['msg' => '关联成功！']);
    }


    public function setChargeAction()
    {
        $id = $this->request->getQuery('staffId', 'string') or die('缺少参数');
        Assets::easyUI();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/staff/setCharge.js');
        $this->view->pick('staff/setCharge');
        $staff = XhhrmStaff::findFirst($id);
        $arr = [];
        if ($staff->sChargeDeps == null) {
            $arr['chargeDep'] = json_encode(array('chargeDep' => ''));
        } else {
            $arr['chargeDep'] = json_encode(array('chargeDep' => $staff->sChargeDeps));
        }
        $this->view->setVars($arr);
    }

    /**
     * 获取负责人
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181109
     */
    public function getChargeAction()
    {
        try {
            $depArr = $this->request->getPost('depArr', 'string');
            $depArr = array_filter($depArr);
            if (!$depArr) {
                return $this->response->setJsonContent(['code' => 200, 'msg' => ''], JSON_UNESCAPED_UNICODE);
            }
            $depEnum = XhhrmDepart::getDepEnum();
            $resultStr = '';
            foreach ($depArr as $depId) {
                $userArr = XhhrmStaff::find([
                    'columns'    => "sStaffName",
                    'conditions' => " CONCAT(',',sChargeDeps,',') like :key:  ",
                    'bind'       => ['key' => '%,'.$depId.',%'],
                ])->toArray();
                if ($userArr) {
                    $depName = Tool::getValue($depEnum, $depId, '');
                    $resultStr .= $depName .'的负责人:'.implode(',', array_column($userArr, 'sStaffName')).';<br>';
                }
            }
            return $this->response->setJsonContent(['code' => 200, 'msg' => $resultStr], JSON_UNESCAPED_UNICODE);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    public function saveChargeAction()
    {
        try {
            $id = $this->request->getPost('id', 'string');
            if (!$id) {
                return $this->sendErrorResponse(500, '缺少参数');
            }
            $sChargeDeps = $this->request->getPost('sChargeDeps', 'string');
            $sChargeDepStr = null;
            if ($sChargeDeps) {
                $depIdArr = array_keys(XhhrmDepart::getDepEnum());
                foreach ($sChargeDeps as $index => $chargeDep) {
                    if (!in_array($chargeDep, $depIdArr)) {
                        unset($sChargeDeps[$index]);
                    }
                }
                $sChargeDeps = array_values($sChargeDeps);
                $sChargeDepStr = implode(',', $sChargeDeps);
            }

            $this->db->begin();
            if ($sChargeDeps) {
                foreach ($sChargeDeps as $depId) {
                    $userArr = XhhrmStaff::find([
                        'conditions' => " CONCAT(',',sChargeDeps,',') like :key: ",
                        'bind'       => ['key' => '%,'.$depId.',%'],
                    ]);
                    foreach ($userArr as $user) {
                        $chargeDepArr = array_values(array_filter(explode(',', $user->sChargeDeps)));
                        if ($chargeDepArr) {
                            foreach ($chargeDepArr as $index => $chargeDep) {
                                if ($chargeDep == $depId) {
                                    unset($chargeDepArr[$index]);
                                }
                            }
                            $chargeDepArr = array_values($chargeDepArr);
                            if ($chargeDepArr) {
                                $user->sChargeDeps = ','.implode(',', $chargeDepArr).',';
                            } else {
                                $user->sChargeDeps = null;
                            }
                            if (!$user->save()) {
                                throw new XhException('清除该部门负责人失败');
                            }
                        }
                    }
                }
            }
            $staff = XhhrmStaff::findFirst($id);
            $staff->sChargeDeps = $sChargeDepStr;
            if (!$staff->save()) {
                $this->db->rollback();
                $this->sendErrorResponse('500', '保存失败');
            }
            $this->db->commit();
            $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }

    }


    /**
     * 导入考勤
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/9/18
     */
//    public function importAttendDataAction()
//    {
//        try {
//            $file = $this->request->getUploadedFiles()[0];
//            $fileName = md5_file($file->getTempName()) . '.' . $file->getExtension();
//            $savePath = TEMP_PATH;
//            if (!is_dir($savePath)) {
//                mkdir($savePath, 0777, true) or die($savePath . '创建失败');
//            }
//            $filePath = $savePath . '/' . $fileName;
//            $file->moveTo($filePath);
//        } catch (\Exception $e) {
//            echo $e->getMessage();
//            die();
//        }
////        $filePath = TEMP_PATH .'/'. 'd1766e9bdec811eebf460688881a3e26.xlsx';
//        try {
//            $kk = Tool::readExcel($filePath, true)['data'];
////            var_dump($kk);die;
//            $dateIndex = explode('：', $kk[0][0]);
//            $dateIndex = end($dateIndex);
//            $dateArr = explode('至', $dateIndex);
//            $first = explode('-', $dateArr[0]);
//            $second = explode('-', $dateArr[1]);
//            $firstPix = $first[0] . '-' . $first[1];
//            $secondPix = $second[0] . '-' . $second[1];
//            $firstPix = trim($firstPix);
//            $secondPix = trim($secondPix);
//            $title = array_filter($kk[1]);
////            var_dump($title);die;
//            $dateTitle = [];
//            $pix = $firstPix;
//            foreach ($title as $index => $value) {   //处理相应序号所对应的日期
//                if ($index == 0) {
//                    $dateTitle[0] = 'staffName';
//                    continue;
//                }
//                if ($value == 1) {
//                    $pix = $secondPix;
//                }
//                $dateTitle[$index] = $pix . '-' . $value;
//            }
////            var_dump($dateTitle);die;
////            var_dump($kk);die;
//            $dataSource = [];
//            foreach ($kk as $index => $row) {  //处理数据
//                if ($index < 2) {
//                    continue;
//                }
////                $user = array_filter($kk[$index - 1]);
////                $data = $kk[$index];
////                $iStaffNum = $user[2];
//                $sStaffName = $row[0];//名字
//
//                foreach ($row as $key => $day) {
//                    if ($key == 0) {
//                        continue;
//                    }
//                    $item = [];
//                    $count = preg_match_all('/([01]?\d|2[0-3]):[0-5]?\d/', $day, $arr);   //匹配时间格式 00:00 ALL
//                    $item['sTrueRec'] = implode(',', $arr[0]);
//                    $signIn = $signOut = null;
//                    if ($count == 1) {  //匹配一次
//                        if (intval(explode(':', $arr[0][0])[0]) > 12) {
//                            $signOut = $arr[0][0];
//                        } else {
//                            $signIn = $arr[0][0];
//                        }
//                        if (isset($data[$key + 1])) {
//                            $iyester = preg_match_all('/0[0-5]:[0-5]?\d/', $row[$key + 1], $yesterday);
//                            if ($iyester != 0) {
//                                $signOut = end($yesterday[0]);
//                                $item['iSignStatus'] = 2;
//                            }
//                        }
//                    } else if ($count > 2) { //匹配大于2次
//                        $iyester = preg_match_all('/0[0-5]:[0-5]?\d/', $day, $yesterday); //匹配前一天的工作 00:00--05:59
//                        foreach ($arr[0] as $index => $value) {
//                            if ($iyester != 0) {
//                                foreach ($yesterday[0] as $yesday) {
//                                    if ($value == $yesday) {
//                                        unset($arr[0][$index]);
//                                    }
//                                }
//                            }
//                            if ($index != ($count - 1) && (explode(":", $value)[0] == explode(":", $arr[0][$index + 1])[0])) { //除去通一时间下重复
//                                unset($arr[0][$index]);
//                            }
//                        }
//                        $arr[0] = array_values($arr[0]);
//                        $signIn = current($arr[0]);
//                        $signOut = end($arr[0]);
//                    } else if ($count == 2) { //两次
//                        $signIn = $arr[0][0];
//                        $signOut = $arr[0][1];
//                    } else if ($count < 1) { //一次都没匹配成功
//                        $signIn = null;
//                        $signOut = null;
//
//                    }
//                    if (isset($signIn)) {
//                        $item['tSiginIn'] = $signIn;
//                        if ($signIn > '09:00') {
//                            $item['iSignIn'] = 3;
//                        }
//                    } else {
//                        $item['iSignIn'] = 2;
//                    }
//                    if (isset($signOut)) {
//                        $item['tSiginOut'] = $signOut;
//                        if ($signOut < '17:30') {
//                            $item['iSignOut'] = 3;
//                        }
//                    } else {
//                        $item['iSignOut'] = 2;
//                    }
//                    if (isset($item['iSignStatus']) && $item['iSignStatus'] == 2) {
//                        $item['iSignOut'] = 1;
//                    }
//                    if (isset($signIn) && isset($signOut)) {
//                        if ($signIn <= '09:00' && $signOut >= '21:00') {
//                            $item['bOvertime'] = 1;
//                        }
//                        if (isset($item['iSignStatus']) && $item['iSignStatus'] == 2) {
//                            $item['bOvertime'] = 1;
//                        }
//                    }
//
//                    if (isset($dateTitle[$key])) {
//                        $item['tDay'] = $dateTitle[$key];
//                    } else {
//                        continue;
//                    }
//                    $item['sStaffName'] = $sStaffName;
////                    $item['iStaffNumber'] = $iStaffNum;
//                    $dataSource[] = $item;
//                }
//            }
////            var_dump($dataSource);die;
//            $flag = true;
//            foreach ($dataSource as $index => $row) {
//                $obj = XHHrmAttendence::findFirst([
//                    'conditions' => 'bDelete=0 AND sStaffName=:sStaffName: AND tDay=:tDay:',
//                    'bind' => ['sStaffName' => $row['sStaffName'], 'tDay' => $row['tDay']],
//                ]);
//                if (!$obj) {
//
//                    $obj = new XHHrmAttendence();
//                } else { //更新时不修改状态
//                    unset($row['iSignOut']);
//                    unset($row['iSignIn']);
//                    unset($row['iSignStatus']);
//                    unset($row['bOvertime']);
//                }
//                $obj->assign($row);
//                if (!$obj->save()) {
//                    $flag = false;
//                    continue;
//                }
//            }
//            if ($flag) {
//                return $this->sendSuccessResponse('插入成功');
//            } else {
//                return $this->sendErrorResponse(500, '插入失败');
//            }
//
//        } catch (\Exception $e) {
//            return $this->response->setContent($e->getMessage());
//        }
//    }

    /**
     * 考勤记录表
     *
     * created by dale 2017/9/18
     */
//    public function attendListAction()
//    {
//        Assets::easyUI();
//        Assets::importJs('js/staff/attendList.js');
//        $this->view->pick('staff/attendList');
//        Template::exists('attendList', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
//        $listButtonArr = $formButtonArr = $listSearchArr = array();
//        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_importRec', 'text' => '导入', 'icon' => 'fa-plus');
//        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_StartTime', 'width' => '100px');
//        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_EndTime');
//        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
//
//        $this->view->setVars(array(
//            'attendList' => Template::createList('attendList', 'attendList', [
//                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
//                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
//            ]),
//        ));
//    }

    /**
     * 导入表单
     */
//    public function importAttendAction()
//    {
//        $this->view->pick('staff/importForm');
//        Assets::importMainJs('assets/jquery/jquery.form.js');
//        Assets::importMainJs('assets/xh/xhExtra.js');
//        Assets::importJs('js/myMain.js');
//        Assets::importJs('js/staff/importAttend.js');
//    }

//    public function getAttendAction()
//    {
//        $key = $this->request->getPost('key', 'string');
//        $startTime = $this->request->getPost('startTime', 'string');
//        $endTime = $this->request->getPost('endTime', 'string');
//        $builder = $this->modelsManager->createBuilder()
//            ->from('Hrm\Models\XHHrmAttendence')
//            ->where('bDelete=0')->orderBy('tDay');
//
//        if ($startTime && $endTime) {
//            $builder->andWhere(
//                'tDay >= :startTime: AND tDay <= :endTime: ',
//                ['startTime' => $startTime, 'endTime' => $endTime]
//            );
//        }
//        if ($key) {
//            $builder->andWhere('sStaffName like :key:', array('key' => '%' . $key . '%'));
//        }
//
//        $totals = $builder->columns('*')->orderBy('tDay')->getQuery()->execute()->toArray();
//        $newArray = [];
//        foreach ($totals as $val) {
//            $newArray[$val['sStaffName']][] = $val;
//        }
////        var_dump($newArray);die;
//        unset($totals);
//        $items = []; //总记录
//        foreach ($newArray as $index => $array) {
//            $sigInC = 0;
//            $sigOutC = 0;
//            $dayNum = 0;
//            $unSignIn = 0;
//            $unSignOut = 0;
//            $overTime = 0;
//            $item = [];
//            foreach ($array as $row) {
//                if ($row['iSignIn'] == 3) {
//                    $sigInC++;
//                } else if ($row['iSignIn'] == 2) {
//                    $unSignIn++;
////                    var_dump($row);
//                }
//                if (isset($row['tSiginIn']) || isset($row['tSiginOut'])) {
//                    $dayNum++;
//                }
//                if ($row['iSignOut'] == 3) {
//                    $sigOutC++;
//                } else if ($row['iSignOut'] == 2) {
//                    $unSignOut++;
//                }
//                if ($row['bOvertime'] == 1) {
//                    $overTime++;
//                }
//            }
//
//            $item['sigInC'] = $sigInC;
//            $item['sigOutC'] = $sigOutC;
//            $item['dayNum'] = $dayNum;
//            $item['unSignOut'] = $unSignOut;
//            $item['unSignIn'] = $unSignIn;
//            $item['overTime'] = $overTime;
//            $items[$index] = $item;
//        }
////        var_dump($items);die;
//        $builder->columns('sStaffName')->groupBy('sStaffName');
//        $data = Main::runBuilderPaginator($builder, true);
//        foreach ($data['rows'] as $index => $row) {
//            $data['rows'][$index] = array_merge($row, $items[$row['sStaffName']]);
//        }
//        return $this->sendJsonResponse($data);
//
//    }


//    public function attendDetailAction()
//    {
//        Assets::easyUI();
//        Assets::importJs('js/staff/attendDetail.js');
//        Assets::importJs('js/myMain.js');
//        $this->view->pick('staff/attendDetail');
//        Template::exists('attendDetail', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
//        $listButtonArr = $formButtonArr = $listSearchArr = array();
////        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_StartTime','width'=>'100px');
////        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_EndTime');
////        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
//        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_signStatus', 'text' => '打卡状态');
//        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_signIn', 'text' => '签到状态');
//        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_signOut', 'text' => '签退状态');
//        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_Overtime', 'text' => '是否加班');
//            $this->view->setVars(array(
//                'attendDetail' => Template::createList('attendDetail', 'attendDetail', [
////                'searchToolbar' => Template::createSearchToolBar($listSearchArr, false),
//                    'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
//                ]),
//            ));
//    }

//    public function getAttendDetailAction()
//    {
//        $sStaffName = $this->request->getPost('sStaffName', 'string');
//        $startTime = $this->request->getPost('startTime', 'string');
//        $endTime = $this->request->getPost('endTime', 'string');
//        $order = $this->request->getPost('order', 'string');
//        $sort = $this->request->getPost('sort', 'string');
//        $builder = $this->modelsManager->createBuilder()
//            ->from('Hrm\Models\XHHrmAttendence')
//            ->where('bDelete=0');
//        if ($sStaffName) {
//            $builder->andWhere('sStaffName = :sStaffName:', array('sStaffName' => $sStaffName));
//        }
//        if ($order & $sort) {
//            $builder->orderBy('' . $sort . ' ' . $order . ' ');
//        } else {
//            $builder->orderBy('tDay');
//        }
//        if ($startTime && $endTime) {
//            $builder->andWhere('tDay>=:startTime: AND tDay<=:endTime: ', array('startTime' => $startTime, 'endTime' => $endTime));
//        }
//
//        $enums = self::$enums;
//        $weekarray = array(0 => "日", 1 => "一", 2 => "二", 3 => "三", 4 => "四", 5 => "五", 6 => "六");
//        $data = Main::runBuilderPaginator($builder, true);
//        foreach ($data['rows'] as $index => $row) {
//            if ($row['iSignStatus'] == 1) {
//                if ($row['iSignIn'] == 1 && $row['iSignOut'] == 1) {
//                    $data['rows'][$index]['sIconStatus'] = '<i class="fa fa-star" aria-hidden="true" style="color: #00aced"></i>';
//                } else {
//                    $data['rows'][$index]['sIconStatus'] = '<i class="fa fa-star" aria-hidden="true" style="color:red"></i>';
//                }
//            } else if ($row['iSignStatus'] == 3 || $row['iSignStatus'] == 4) {
//                $data['rows'][$index]['sIconStatus'] = '<i class="fa fa-star" aria-hidden="true" style="color: #00aced"></i>';
//            } else {
//                $data['rows'][$index]['sIconStatus'] = '<i class="fa fa-star" aria-hidden="true" style="color:#00ee00"></i>';
//            }
//            $data['rows'][$index]['tDay'] = $row['tDay'] . "(星期" . $weekarray[date("w", strtotime($row['tDay']))] . ')';
//            if (date("w", strtotime($row['tDay'])) == 6 || date("w", strtotime($row['tDay'])) == 0) {
//                $data['rows'][$index]['bColor'] = 1;
//            } else {
//                $data['rows'][$index]['bColor'] = 0;
//            }
//            $data['rows'][$index]['iSignIn'] = $enums['iSignIn'][$row['iSignIn']];
//            $data['rows'][$index]['iSignOut'] = $enums['iSignOut'][$row['iSignOut']];
//            $data['rows'][$index]['iSignStatus'] = $enums['iSignStatus'][$row['iSignStatus']];
//            $data['rows'][$index]['bOvertime'] = $enums['bOvertime'][$row['bOvertime']];
//        }
//
//        return $this->sendJsonResponse($data);
//
//    }

//    public function changeAttendAction()
//    {
//        try {
//            $ids = $this->request->getPost('ids', 'string') or die('缺少参数');
//            $status = $this->request->getPost('status', 'string');
//            $sin = $this->request->getPost('sin', 'string');
//            $out = $this->request->getPost('out', 'string');
//            $overtime = $this->request->getPost('overtime', 'string');
//            $ids = explode(',', $ids);
//            $objs = XHHrmAttendence::find([
//                'conditions' => 'bDelete=0 AND iAttId in ({ids:array})',
//                'bind' => ['ids' => $ids],
//            ]);
//        } catch (\Exception $e) {
//            echo $e->getMessage();
//            die();
//        }
//        $res = true;
//        if (isset($status)) {
//            foreach ($objs as $obj) {
//                $obj->iSignStatus = $status;
//                if (!$obj->save()) {
//                    $res = false;
//                }
//            }
//        }
//        if (isset($sin)) {
//            foreach ($objs as $obj) {
//                $obj->iSignIn = $sin;
//                if (!$obj->save()) {
//                    $res = false;
//                }
//            }
//        }
//        if (isset($out)) {
//            foreach ($objs as $obj) {
//                $obj->iSignOut = $out;
//                if (!$obj->save()) {
//                    $res = false;
//                }
//            }
//        }
//        if (isset($overtime)) {
//            foreach ($objs as $obj) {
//                $obj->bOvertime = $overtime;
//                if (!$obj->save()) {
//                    $res = false;
//                }
//            }
//        }
//        if ($res) {
//            return $this->sendSuccessResponse('修改成功');
//        } else {
//            return $this->sendSuccessResponse('修改失败');
//        }
//    }

    /**
     * 通讯录
     *
     * created by dale 2017116
     */
    public function addressBookAction()
    {
        Assets::easyUI();
        Assets::importJs('js/staff/addressBook.js');
        $this->view->pick('staff/addressBook');

        Template::exists('bookList', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $listSearchArr = array();

        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        if (UserPower::checkUserPower('AddrBook_AllotSchool')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_auth', 'text' => '分配学校', 'icon' => 'fa-pencil');
        }
        if(UserPower::checkUserPower('AddrBook_MoveGroup')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_manageGroup', 'text' => '转移', 'icon' => 'fa-pencil');
        }
        $this->view->setVars(array(
            'bookList' => Template::createList('bookList', 'bookList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
            'nowUserId' => Main::getLoginUserInfo('userId'),
        ));
    }

    /**
     * 创建人员账号
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180416
     */
    public function createAccountAction(){
        $phone = $this->request->getPost('phone','string');
        $name  = $this->request->getPost('name','string');
        if(!$phone || !$name){
            return $this->sendErrorResponse(500,'创建失败');
        }
        try{
            $res = $this->createNewAccount($phone,$name);
            if(!$res){
                return $this->sendErrorResponse(500,'账号创建失失败');
            }
            $this->praseLog('创建成功','创建成功');
            return $this->response->setJsonContent(['code' => 200, 'msg' =>'创建成功'], JSON_UNESCAPED_UNICODE);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }



    /**
     * 根据手机号，用户姓名创建账号
     *
     * @param $phoneNum
     * @param $staffName
     * @param string $pwd
     * @return bool
     * @throws \Exception
     *
     * create by ck 20171113
     * modify by ck 20180627
     */
    private function createNewAccount($phoneNum, $staffName, $pwd = '123456')
    {
        $user = new XhsysUser();
        $user->sLogonName   = $phoneNum;
        $user->sUserName    = $staffName;
        $user->sLogonPwd    = strtoupper(md5($pwd));
        $user->sSelfPhone   = $phoneNum;
        $user->iUserType    = 5;
        $user->iSchoolId    = 1;
        $user->bCompany     = 1;
        return $user->insertAfterOld();
    }

    /**
     * 组织树
     * create by dale 20180306
     */
    public function orgTreeAction(){
        $this->view->pick('staff/orgTree');
        Assets::jOrgChart();
        Assets::importJs('js/staff/orgTree.js');
        $staffs = XhhrmStaff::find([
            'columns'    => 'iUserId,sChargeDeps,sStaffName,sSelfPhone',
            'conditions' => 'bDelete = 0 AND sChargeDeps is not null',
        ])->toArray();

        $arr = [];
        foreach ($staffs as $staff){
            $deps = array_filter(explode(',',$staff['sChargeDeps']));
            foreach ($deps as $dep){
                $arr[$dep] = $staff;
            }
        }
        $deps = Hrm::getDepArray();
        $org = $this->recursionArray($deps,$arr);
        $this->view->setVars([
            'data' => $org
        ]);

    }


    public function  recursionArray($deps,$maregArr){
        foreach ($deps  as $index => $row){
            if(isset($maregArr[$row['id']])){
                $deps[$index] = array_merge($deps[$index],$maregArr[$row['id']]);
            }
            if(isset($row['child'])){
                $deps[$index]['child'] =  $this->recursionArray($deps[$index]['child'],$maregArr);
            }
        }
        return $deps;
    }

    /**
     * 备用人才库列表
     * create by dale 20180326
     */
    public function resourcesAction(){
        Assets::easyUI();
        Assets::sweetAlert2();
        Assets::datetimePicker();
        Assets::importJs('js/staff/resources.js');
        $this->view->pick('staff/resources');

        $enums = self::$enums;
        $enums['iWorkStatus'][''] = '工作状态';
        Template::exists('resource', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_move', 'text' => '转移', 'icon' => 'fa-pencil');
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');

        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_state', 'text' => '状态', 'class' => 'bt_list_menu');
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_see', 'text' => '查看', 'icon' => 'fa-eye');
        $state = self::$state;
        $state[''] = '全部';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_state', 'data' => $state, 'default' => '');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $this->view->setVars(array(
            'staffList' => Template::createList('staffList', 'resource', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ])
        ));
    }

    /**
     * 保存人才资源库
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180326
     */
    public function saveResourceAction(){
        try {
            $iStaffId = $this->request->getPost('iStaffId');
            $iDepId = $this->request->getPost('iDepId');
            if ($iStaffId == null) {
                $obj = new XhhrmResource();
            } else {
                $obj = XhhrmResource::findFirst([
                    'conditions' => 'bDelete=0 AND  iStaffId=:iStaffId:',
                    'bind' => array('iStaffId' => $iStaffId)
                ]);
            }
            $obj->assign($this->request->getPost());
            $obj->iUserSex = $this->request->getPost('iUserSex', 'int') ?: null;
            $obj->bMarried = $this->request->getPost('bMarried', 'int') ?: null;
            $obj->iSignNumber = $this->request->getPost('iSignNumber', 'int') ?: null;

            $obj->tBirthday = $this->request->getPost('tBirthday', 'string') ?: null;
            $obj->tGraduateDate = $this->request->getPost('tGraduateDate', 'string') ?: null;
            if (isset($iDepId) && $iDepId != 0) {
                $obj->sDepIds = $this->getDepIds($iDepId);
            }
            if ($obj->save()) {
                $this->praseLog('信息保存成功', '信息保存成功');
                return $this->response->setContent('succcess');
            } else {
                $this->praseLog('信息保存失败', '信息保存失败');
                return $this->response->setContent('error');
            }
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }

    /**
     * 获取人员
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180327
     */
    public function getResourceAction(){
        $key = $this->request->getPost('key', 'string'); //可以为空
        $iDepId = $this->request->getPost('depId', 'string');
        $state  = $this->request->getPost('state','string');
        try{
            $builder = $this->modelsManager->createBuilder()
                ->columns(['s.iStaffId', 's.sNativePlace', 's.sStaffName', 's.sDepIds','s.sPostName',
                    's.tBirthday', 's.iUserSex', 's.bMarried', 's.sNationName', 's.sIdentityCode',
                    's.sNowAddress', 's.sFamilyAddress', 's.sSelfPhone','s.iState','s.tTime'])
                ->from(['s' => 'Admin\Models\hrm\XhhrmResource'])
                ->where('s.bDelete=0');

            if ($key) {
                $builder->andWhere('s.sStaffName like :key: OR s.sSelfPhone like :key: OR s.sPostName like :key: ', array('key' => '%' . $key . '%'));
            };
            if ($iDepId) {
                $builder->andWhere('sDepIds LIKE :sDepIds:', array('sDepIds' => '%,' . $iDepId . ',%'));
            }
            if($state || $state === '0'){
                $builder->andWhere(' iState = :state:',['state'=>$state]);
            }

            $data = Main::runBuilderPage($builder);
            foreach ($data['rows'] as $index => $row) {
                $data['rows'][$index]['info'] = '<i class="fa fa-user" style="color:' . $this->resourceColor($row['iState']) . ';" ></i>';
                if ($row['tBirthday'] != null) {
                    $data['rows'][$index]['iAge'] = $this->getAge($row['tBirthday']);
                }
                if (isset($row['sDepIds'])) {
                    $data['rows'][$index]['sDepName'] = XhhrmDepart::getDepName($row['sDepIds']);
                }
                $data['rows'][$index]['iUserSex'] = self::$enums['iUserSex'][$row['iUserSex']];
                $data['rows'][$index]['bMarried'] = self::$enums['bMarried'][$row['bMarried']];
                $data['rows'][$index]['iState'] = self::$state[$row['iState']];
            }

            return $this->sendJsonResponse($data);
        }catch (\Exception $e){
            return $this->sendErrorResponse(400,$e->getMessage());
        }

    }

    public function resourceColor($state){
        switch ($state){
            case 1 : return 'red';  //未录取
            case 2 : return '#66CC00'; //待入职
            case 3 : return '#FFCC00';   //未入职
            case 4 : return '#2baab1'; //已入职
            default: return 'white';
        }
    }


    /**
     * 人力表单
     * create by dale 20180326
     */
    public function resourceFormAction($id){
        $this->view->pick('staff/resourceForm');
        Assets::importJs('js/myMain.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::datetimePicker();
        Assets::easyUI();
        Assets::importJs('js/staff/resourceForm.js');
        $webArr = ['iStaffLevel' => XhsysEnum::getEnumByNodeName('职位等级'),];
        if($id){
            $info = XhhrmResource::findFirst($id);
            $webArr['staffInfo'] = json_encode($info);
        }

        $this->view->setVars($webArr);
    }


    /**
     * 改变状态
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180327
     */
    public function resourceStateAction(){
        $id = $this->request->getPost('id');
        $state = $this->request->getPost('state');
        $time  = $this->request->getPost('time');
        $desc  = $this->request->getPost('desc');
        if(!$id || !$state || !$time){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        try{
            $obj = XhhrmResource::findFirst($id);
            if (!$obj->sStaffName || !$obj->sIdentityCode) {
                return $this->sendErrorResponse(500, '缺少身份证号码或者名字');
            }
            if($obj->iState == 4) {
                return $this->sendErrorResponse(400,'该员工已入职');
            }

            if($obj->sTime == null){
                $obj->sTime = json_encode([['time'=>$time,'state'=>$state,'desc'=>$desc,'operator'=>Main::getLoginUserInfo('userId'),'operateTime'=>date("Y-m-d H:i:s",time())]]);
            }else{
                $arr = json_decode($obj->sTime,true);
                $arr[] = ['time'=>$time,'state'=>$state,'desc'=>$desc,'operator'=>Main::getLoginUserInfo('userId'),'operateTime'=>date("Y-m-d H:i:s",time())];
                $obj->sTime = json_encode($arr);
            }
            $obj->iState = $state;
            if($state == 2 || $state == 4 ){
                $obj->tTime = $time;
            }
            if(!$obj->save()){
                return $this->sendErrorResponse(500,'保存失败');
            }
            if($obj->iState == 4){ //创建账号
                $staff = $obj->toArray();
                $staff['iStaffId']  = null;
                $staff['tHireDate'] = $time;
                $newObj = new XhhrmStaff();
                $newObj->sCreateMode = 'resource_changeStates';
                $newObj->assign($staff);
                if ($this->checkStaff($staff['sStaffName'], $staff['sIdentityCode'])) {
                    if(!$newObj->save()){
                        return $this->sendErrorResponse(500,'职工信息保存失败');
                    }
                    $user = XhsysUser::findFirst([
                        'conditions' => 'bDelete=0 AND sSelfPhone=:phone: AND sUserName = :name:',
                        'bind' => ['phone' => $newObj->sSelfPhone, 'name' => $newObj->sStaffName],
                    ]);
                    if (!$user) {
                        $res = $this->createNewAccount($newObj->sSelfPhone, $newObj->sStaffName);
                        if (!$res) {
                            return $this->sendErrorResponse(500,'账号创建失败');
                        }
//                        if(!$user){
//                            return $this->sendErrorResponse(500,'找不到用户');
//                        }
                    }

                    $newObj->iUserId = $user->iUserId;
                    if(!$newObj->save()){
                        return $this->sendErrorResponse(500,'关联失败');
                    }
                }
            }
            return $this->sendJsonResponse(['code'=>200,'msg'=>'保存成功']);

        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }

    }

    /**
     * 状态表单
     * @param $state
     * @param $id
     * create by dale 20180328
     */
    public function stateFormAction($state,$id){
        $this->view->pick('staff/stateForm');
        Assets::datetimePicker();

        $this->view->setVars([
            'state' => $state,
            'id'    => $id,
        ]);
    }


    /**
     * 状态表格see
     * @param $id
     * @return string
     * create by dale 20180328
     */
    public function stateTableAction($id = null)
    {
        $this->view->pick('staff/stateTable');
        if(!$id){
            return $this->sendViewError('缺少参数');
        }
        $info = XhhrmResource::findFirst($id)->sTime;
        if ($info) {
            $info = json_decode($info,true);
        } else {
            $info = [];
        }
        if ($info) {
            Main::runUserNameById($info,['operator'=>'operator'],true);
            foreach ($info as $index => $row){
                $info[$index]['state'] = self::$state[$row['state']];
            }
        }
        $this->view->setVars([
            'info' => $info,
        ]);
    }

    /**
     * 设置staff详情
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181017
     */
    public function staffHisDetailAction()
    {
        try {
            $staffId = $this->request->getQuery('staffId', 'int');
            if (!$staffId) {
                return $this->sendViewError('缺少staffId');
            }
            $staff = XhhrmStaff::findFirst($staffId);
            if (!$staff) {
                return $this->sendViewError('未找到记录');
            }
            $this->view->pick('staff/staffHisDetail');
            $info = $staff->toArray();
            if ($info['mHistory']) {
                $info['mHistory'] = json_decode($info['mHistory'], true);
                if ($info['mHistory']) {
                    foreach ($info['mHistory'] as &$item) {
                        $item['status'] = self::$enums[$item['type']][$item['status']];
                    }
                }
                Main::runUserNameById($info['mHistory'], ['operator' => 'operatorName'], true);
            } else {
                $info['mHistory'] = [];
            }

//            Assets::importJs('js/staff/staffHisDetail.js');
            return $this->view->setVars([
                'info' => $info,
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }



//    /**
//     * 审核列表
//     *
//     * create by dale  20181102
//     */
//    public function testAction()
//    {
//
//        $arr = json_decode(json_encode((array) simplexml_load_string($str)), true);
//        $newArr = [];
//        $userArr = $arr['user'];
//        foreach ($userArr as $user) {
//            $newArr[] = $user['@attributes']['name'];
//        }
//        return $newArr;
//    }

    /**
     * 获取邮箱用户列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181128
     */
//    public function getMailUserInfoArrAction()
//    {
//        try {
//            $domain = $this->request->getQuery('domain');
//            $data = HundredMail::getUserList($domain);
//            return $this->sendJsonResponse($data);
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }

//    public function convertStaffNameToNumberAction()
//    {
//        try {
//            $emailArr = $this->testAction();
//            $endPref = '@100fen.cn';
//            $staffObjArr = XhhrmStaff::find([
//                'conditions' => 'bDelete= 0 and iStaffStatus = 1',
//            ]);
//            foreach ($staffObjArr as $staff) {
//                if ($staff->sHundredMail) {
//                    continue;
//                }
//                if ($staff->sSelfPhone) {
//                    if (in_array($staff->sSelfPhone.$endPref,$emailArr)) {
//                        $staff->sHundredMail = $staff->sSelfPhone.$endPref;
//                        if (!$staff->save(null, null, false)) {
//                            $this->praseLog($staff->sStaffName.'百分邮箱保存失败',$staff->sStaffName.'百分邮箱保存失败');
//                            continue;
//                        }
//                        continue;
//                    }
//                }
//                $englishName = $this->getUserEnglish($staff->sStaffName);
//                if (in_array($englishName.$endPref, $emailArr)) {
//                    $staff->sHundredMail = $englishName.$endPref;
//                    if (!$staff->save(null, null, false)) {
//                        $this->praseLog($staff->sStaffName.'百分邮箱保存失败',$staff->sStaffName.'百分邮箱保存失败');
//                        continue;
//                    }
//                    continue;
//                }
//            }
//            return $this->sendSuccessResponse('邮箱处理成功');
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }

    /**
     * 获取名称 英文首字母 小写
     *
     * @param $name
     *
     * @return string
     *
     * create by dale  20181128
     */
    public function getUserEnglish($name)
    {
        if (!$name) {
            return '';
        }
        $chineseArr =$this->mbStrSplit($name);
        $englishName = '';
        foreach ($chineseArr as $chinese) {
            $englishName .= strtolower($this->getFirst($chinese));
        }
        return $englishName;
    }

    /**
     * 字符切割
     *
     * @param $string
     * @param int $len
     *
     * @return array
     *
     * create by dale  20181128
     */
    function mbStrSplit($string, $len=1) {
        $start = 0;
        $strlen = mb_strlen($string);
        while ($strlen) {
            $array[] = mb_substr($string,$start,$len,"utf8");
            $string = mb_substr($string, $len, $strlen,"utf8");
            $strlen = mb_strlen($string);
        }
        return $array;
    }

    private function getFirst($str)
    {
        $str= iconv("UTF-8","gb2312", $str);//编码转换
        if (preg_match("/^[\x7f-\xff]/", $str))
        {
            $fchar=ord($str{0});
            if($fchar>=ord("A") and $fchar<=ord("z") )return strtoupper($str{0});
            $a = $str;
            $val=ord($a{0})*256+ord($a{1})-65536;
            if($val>=-20319 and $val<=-20284)return "A";
            if($val>=-20283 and $val<=-19776)return "B";
            if($val>=-19775 and $val<=-19219)return "C";
            if($val>=-19218 and $val<=-18711)return "D";
            if($val>=-18710 and $val<=-18527)return "E";
            if($val>=-18526 and $val<=-18240)return "F";
            if($val>=-18239 and $val<=-17923)return "G";
            if($val>=-17922 and $val<=-17418)return "H";
            if($val>=-17417 and $val<=-16475)return "J";
            if($val>=-16474 and $val<=-16213)return "K";
            if($val>=-16212 and $val<=-15641)return "L";
            if($val>=-15640 and $val<=-15166)return "M";
            if($val>=-15165 and $val<=-14923)return "N";
            if($val>=-14922 and $val<=-14915)return "O";
            if($val>=-14914 and $val<=-14631)return "P";
            if($val>=-14630 and $val<=-14150)return "Q";
            if($val>=-14149 and $val<=-14091)return "R";
            if($val>=-14090 and $val<=-13319)return "S";
            if($val>=-13318 and $val<=-12839)return "T";
            if($val>=-12838 and $val<=-12557)return "W";
            if($val>=-12556 and $val<=-11848)return "X";
            if($val>=-11847 and $val<=-11056)return "Y";
            if($val>=-11055 and $val<=-10247)return "Z";
        }
        else
        {
            return null;
        }
    }


    /**
     * 尝试保存职工json
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190220
     */
    public function tryAddStaffAction()
    {
        $json = $this->request->getQuery('json', 'string');
        if (!$json) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        try {
            $data = json_decode($json, true);
            $this->db->begin();
            XhhrmStaff::addStaff($data);
            //不保存
            $this->db->rollback();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

//    public function testAction()
//    {
//
//
//        $code = '510921199608062528';
////        var_dump(substr($code, 6, 8));die;
//        $day = XhhrmStaff::getBirthdayBysIdentityCode($code);
//        var_dump($day);die;
//
//
//    }






}
